<template>
  <view class="custom-notice-bar" :style="{ backgroundColor: backgroundColor }">
    <view v-if="showIcon" class="custom-notice-bar__icon">
      <text class="icon">🔔</text>
    </view>
    <view class="custom-notice-bar__content">
      <view 
        class="custom-notice-bar__text-wrapper"
        :class="{ 'scroll': scrollable && isAnimationActive }"
        :style="scrollable ? { '--animation-duration': animationDuration + 's' } : {}"
      >
        <text class="custom-notice-bar__text">{{ text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'CustomNoticeBar',
  props: {
    text: {
      type: String,
      default: ''
    },
    scrollable: {
      type: Boolean,
      default: true
    },
    showIcon: {
      type: Boolean,
      default: true
    },
    backgroundColor: {
      type: String,
      default: '#fffbe8'
    },
    color: {
      type: String,
      default: '#de8c17'
    },
    speed: {
      type: Number,
      default: 50
    }
  },
  data() {
    return {
      animationDuration: 0,
      animation: null,
      isAnimationActive: false
    }
  },
  mounted() {
    if (this.scrollable) {
      // 等待1.5秒后启动滚动动画
      setTimeout(() => {
        this.isAnimationActive = true
        this.startScrollAnimation()
      }, 3500)
    }
  },
  watch: {
    text: {
      handler() {
        if (this.scrollable && this.isAnimationActive) {
          this.startScrollAnimation()
        }
      },
      immediate: true
    }
  },
  methods: {
    startScrollAnimation() {
      // 根据文本长度动态调整动画持续时间
      const textLength = this.text.length
      this.animationDuration = Math.max(10, textLength / this.speed * 10)
    }
  }
}
</script>

<style scoped>
.custom-notice-bar {
  display: flex;
  align-items: center;
  padding: 16rpx 20rpx;
  margin: 0 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.custom-notice-bar__icon {
  margin-right: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.custom-notice-bar__icon .icon {
  font-size: 24rpx;
}

.custom-notice-bar__content {
  flex: 1;
  overflow: hidden;
  position: relative;
  height: 40rpx;
  display: flex;
  align-items: center;
}

/* 修改结构，使用wrapper包裹text */
.custom-notice-bar__text-wrapper {
  display: flex;
  align-items: center;
  height: 100%;
}

/* 滚动版本的样式 */
.custom-notice-bar__text-wrapper.scroll {
  animation: customNoticeScroll var(--animation-duration, 15s) linear infinite;
  animation-fill-mode: none;
  /* 确保动画始终运行 */
  animation-play-state: running !important;
}

.custom-notice-bar__text {
  font-size: 28rpx;
  color: #de8c17;
  white-space: nowrap;
  line-height: 40rpx;
  display: inline-block;
}

/* 滚动动画 - 从首位开始 */
@keyframes customNoticeScroll {
  0% {
    transform: translateX(0);
    /* 从首位（容器左侧）开始 */
  }
  100% {
    transform: translateX(-100%);
    /* 滚动到容器左侧完全不可见位置 */
  }
}
</style>